﻿using M_Quality.API.Application.Command.QualityProgromCommand;
using M_Quality.Domain;
using M_Quality.Repository;
using M_Quality.Repository.Impl;
using M_Quality.Repository.Interface;
using MediatR;

namespace M_Quality.API.Application.CommandHandler.QualityProgromCommandHandler
{
    public class QualityProgromUpdateCommandHandler : IRequestHandler<QualityProgromUpdateCommand, int>
    {
        protected readonly IQualityPlanRepositry QualityPlanRepositry;
        protected readonly IQualityprogromRepositry QualityprogromRepositry;

        public QualityProgromUpdateCommandHandler(IQualityPlanRepositry qualityPlanRepositry, IQualityprogromRepositry qualityprogromRepositry)
        {
            QualityPlanRepositry = qualityPlanRepositry;
            QualityprogromRepositry = qualityprogromRepositry;
        }

        public async Task<int> Handle(QualityProgromUpdateCommand request, CancellationToken cancellationToken)
        {

        
            var res = await QualityprogromRepositry.GetAsync(o => o.QualityPlanCode == request.QualityPlanCode);

            var count = 0;
            foreach (var item in res) {
                var pp = await QualityprogromRepositry.GetModelAsync(item.QualityprogramId);
                 pp.QualityPlanCode = request.QualityPlanCode;
                pp.QualitygroupId = request.QualitygroupId;
                count++;
                var count1 = 0;
                foreach (var item2 in request.QualityinspectionId)
                {
                    count1++;
                    if (count == count1)
                    {
                        pp.QualityinspectionId = item2;
                        await QualityprogromRepositry.UpdateAsync(pp);
                    }
                }
            }
             var ss = await QualityPlanRepositry.GetModelAsync(request.QualityPlanId);
            ss.QualityPlanName = request.QualityPlanName;
            ss.QualityPlanSart = request.QualityPlanSart;
            ss.QualityPlanCode = request.QualityPlanCode;
           await QualityPlanRepositry.UpdateAsync(ss);
            return 1;
     }
    
    }
}
